<?php

namespace App\Service\ChatGroup;

use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupModel;
use App\Models\ChatGroup\ChatGroupSessionModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use Illuminate\Redis\Connections\Connection;
use Illuminate\Support\Facades\Redis;

class ChatGroupMessageReadService
{
    private Connection $redis;

    private int $selfUserId;

    public function __construct(int $userId = 0)
    {
        $this->redis      = Redis::connection();
        $this->selfUserId = $userId;
    }

    /**
     * 添加群组未读数
     *
     * @param int $groupId
     * @param int $sessionId
     * @return void
     */
    public function addUnreadMessage(int $groupId, int $sessionId): void
    {
        // 获取群组中的所有用户
        // 是门店的用户 && 第一次说话
        $totalCount = ChatGroupHistoryModel::query()
                                           ->where('sessionId', $sessionId)
                                           ->count();

        if ($totalCount <= 2) {
            return;
        }

        $groupMembers = $this->getGroupMembers($groupId);

        foreach ($groupMembers as $memberId) {
            if ($memberId != $this->selfUserId) {
                // 增加未读消息数量
                $this->increaseUnreadCount($memberId, $groupId);
            }
        }
    }

    /**
     * 阅读消息 - 删除未读数
     *
     * @param int $groupId
     * @return void
     */
    public function readMessage(int $groupId): void
    {
        // 减少未读消息数量
        $this->decreaseUnreadCount($groupId);
    }

    /**
     * 阅读消息 - 删除未读数
     *
     * @param int $shopId
     * @return void
     */
    public function readMessageByShopId(int $shopId): void
    {
        $chatGroup = ChatGroupModel::query()->where('shopId', $shopId)->first();

        $groupId = $chatGroup->id ?? 0;

        // 减少未读消息数量
        $this->readMessage($groupId);
    }

    /**
     * 获取未读数
     *
     * @param int $groupId
     * @return int
     */
    public function getUnreadNums(int $groupId): int
    {
        $key = "chat_group_unread:{$this->selfUserId}:{$groupId}";
        return (int)$this->redis->hGet($key, 'count');
    }

    /**
     * 递增消息未读数
     *
     * @param $userId
     * @param $groupId
     * @return void
     */
    private function increaseUnreadCount($userId, $groupId): void
    {
        $key = "chat_group_unread:{$userId}:{$groupId}";
        $this->redis->hIncrBy($key, 'count', 1);
    }

    /**
     * 减少消息未读数
     *
     * @param $groupId
     * @return void
     */
    private function decreaseUnreadCount($groupId): void
    {
        $key = "chat_group_unread:{$this->selfUserId}:{$groupId}";

        // 减少未读消息数量

        // 直接删除不用频繁-1

        $this->redis->del($key);

        // 如果需要一条条处理, 注释上面,打开下面
        /*$count = $this->redis->hIncrBy($key, 'count', -1);

        if ($count <= 0) {
            // 如果未读消息数量为0，删除这个哈希
            $this->redis->del($key);
        }*/
    }

    /**
     * 获取群组内的用户列表
     *
     * @param int $groupId
     * @return array
     */
    private function getGroupMembers(int $groupId): array
    {
        $userList = ChatGroupUserModel::getUserList($groupId);

        return array_values(array_unique(array_column($userList, 'userId')));
    }
}
